package com.gzsxy.excel.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.util.Date;
import java.util.List;


/**
 * @Author
 * @Description //TODO Excel模板对象
 * @Date 2022/01/08
 * @Param $
 * @return $
**/


public class DateConverter implements Converter<Date> {
    @Override
    public Class supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }


    /**
     * @Description: excel 转换 java 类型 excel 读取会被调用
     * @param: 
     * @return: 
    */
    @Override
    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(StrUtil.isBlank(cellData.getStringValue())) {
            return null;
        }

        String dataStringValue = cellData.getStringValue();
        DateTime parse = DateUtil.parse(dataStringValue);
        return parse.toJdkDate();
    }


    /**
     * @Description: java 转换 excel 类型 excel 写入会被调用
     * @param:
     * @return:
     */
    @Override
    public WriteCellData<?> convertToExcelData(Date value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(DateUtil.format(value, "yyyy-MM-dd"));
    }

    public static String listToString(List list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        int length = sb.toString().length();
        if(length == 0){
            return "";
        }
        return sb.toString().substring(0, sb.toString().length()-1);
    }


//    public static void main(String[] args) {
//        List list = new ArrayList();
//        list.add("50");
//        list.add("100");
//        list.add("700");
//        System.out.println(listToString(list,','));
//    }
}

